﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CommonCodeManagers.plugin
{
    public class JsonOperate
    {
        private string jsonPath = String.Empty;
        private readonly string _template = String.Empty;
        private readonly string _jsonStr = String.Empty;

        public JsonOperate()
        {

        }

        public JsonOperate(string template, string jsonStr)
        {
            _template = template;
            _jsonStr = jsonStr;
        }

        public JsonOperate(string filename)
        {
            jsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename);
        }

        public string ReplaceColumn()
        {
            string resultContent = _template;
            if (string.IsNullOrEmpty(_template) || string.IsNullOrEmpty(_jsonStr))
            {
                return resultContent;
            }

            JObject json = JObject.Parse(_jsonStr);
            foreach (JToken token in json.Children<JToken>())
            {
                if (token.Children().Children().Count() > 1)
                {
                    resultContent = ReplaceArray(resultContent, token.Path, token.Children());
                }
                else
                {
                    string key = token.Path;
                    resultContent = ReplaceContent(resultContent, token.Path, token.Select(b => b.ToString()).First());
                }
            }
            return resultContent;
        }

        private string ReplaceArray(string inputStr, string arrayName, JEnumerable<JToken> token)
        {
            string arrayBegin = $"{{{{{arrayName} Begin}}}}";
            string arrayEnd = $"{{{{{arrayName} End}}}}";
            int startIndex = inputStr.IndexOf(arrayBegin);
            int endIndex = inputStr.IndexOf(arrayEnd);
            if (endIndex <= startIndex)
                return inputStr;
            //获取生成列的内容
            string colContent = inputStr.Substring(startIndex + arrayBegin.Length, endIndex - startIndex - arrayEnd.Length - 2);
            StringBuilder colsAllContent = new StringBuilder();
            for (int i = 0; i < token.Children().Count(); i++)
            {
                string templateContent = colContent;
                var col = token.Children().ToArray()[i];
                for (int j = 0; j < col.Children().Count(); j++)
                {
                    var field = col.Children().ToArray()[j];
                    templateContent = ReplaceContent(templateContent, field.Path.Replace(col.Path + ".", ""), field.Select(b => b.ToString()).First());
                }
                colsAllContent.Append(templateContent);
            }
            inputStr = inputStr.Replace(arrayBegin + colContent + arrayEnd, colsAllContent.ToString());
            return inputStr;
        }

        private string ReplaceContent(string inputStr, string field, string replaceState)
        {
            string templatePattern = $"{{{{{field}(|.*){{0,100}}}}}}";
            Regex replaceRegex = new Regex(templatePattern);
            string[] sonReplaceArr = replaceRegex.Match(inputStr).Value.Split('|');
            if (!replaceRegex.IsMatch(inputStr) || !replaceRegex.Match(inputStr).Value.Contains("|"))
                return replaceRegex.Replace(inputStr, replaceState);
            for (var i = 0; i < (sonReplaceArr.Length - 1) / 2; i++)
            {
                replaceState = replaceState.Replace(sonReplaceArr[i * 2 + 1], sonReplaceArr[(i + 1) * 2].Replace("}}",""));
            }
            return replaceRegex.Replace(inputStr, replaceState);
        }

    }
}